import { CanActivate, ExecutionContext, Injectable } from "@nestjs/common";
import { UserSys } from "src/user/userSys.entity";
import { Http } from "src/util/http";
import { DeptRoleEnum, RoleEnum } from "./role.enum";


@Injectable()
export class RoleGuard implements CanActivate {
    constructor(
        private readonly name: string[]
    ) { }
    async canActivate(
        context: ExecutionContext
    ) {
        const req = context.switchToHttp().getRequest()
        const user = req.user as UserSys
        if (!user.system) throw Http.forbidden("未选择职场", 666)
        if (!this.name.length) return true;
        if (user.role === RoleEnum.boos) return true;//如果是boos

        if (user.role === RoleEnum.director) {//如果用户是总经理并且角色中没有boos
            if (this.name.some(e => e === RoleEnum.boos)) return false;
            return true;
        }
        //如果用户的部门权限或用户的权限符合
        if (this.name.some(e => e === user.role || e === user.dept?.deptRole)) return true;
        throw Http.forbidden("权限不足")
    }
}
export const UserGuard = (user: (RoleEnum | DeptRoleEnum)[] = []) => new RoleGuard(user);

// export const UserGuard = (name: RoleEnum[]) => new RoleGuard(name);
